package org.jeecg.modules.ywSemiFinishedProductEnter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.constant.InventoryConstant;
import org.jeecg.modules.ywSemiFinishedProductEnter.entity.YwSemiFinishedProductEnterDetail;
import org.jeecg.modules.ywSemiFinishedProductEnter.entity.YwSemiFinishedProductEnterMain;
import org.jeecg.modules.ywSemiFinishedProductEnter.service.IYwSemiFinishedProductEnterDetailService;
import org.jeecg.modules.ywSemiFinishedProductEnter.service.IYwSemiFinishedProductEnterMainService;
import org.jeecg.modules.ywSemiFinishedProductEnter.vo.YwSemiFinishedProductEnterMainPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 半成品入库
 * @Author: jeecg-boot
 * @Date: 2024-08-15
 * @Version: V1.0
 */
@Api(tags = "半成品入库")
@RestController
@RequestMapping("/ywSemiFinishedProductEnter/ywSemiFinishedProductEnterMain")
@Slf4j
public class YwSemiFinishedProductEnterMainController {
    @Autowired
    private IYwSemiFinishedProductEnterMainService ywSemiFinishedProductEnterMainService;
    @Autowired
    private IYwSemiFinishedProductEnterDetailService ywSemiFinishedProductEnterDetailService;

    /**
     * 分页列表查询
     *
     * @param ywSemiFinishedProductEnterMain
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "半成品入库-分页列表查询")
    @ApiOperation(value = "半成品入库-分页列表查询", notes = "半成品入库-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(YwSemiFinishedProductEnterMain ywSemiFinishedProductEnterMain,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<YwSemiFinishedProductEnterMain> queryWrapper = QueryGenerator.initQueryWrapper(ywSemiFinishedProductEnterMain, req.getParameterMap());
        if (StringUtils.isNotBlank(ywSemiFinishedProductEnterMain.getBillNo()) ||
                StringUtils.isNotBlank(ywSemiFinishedProductEnterMain.getProductCode()) ||
                StringUtils.isNotBlank(ywSemiFinishedProductEnterMain.getProductName())) {
            List<YwSemiFinishedProductEnterDetail> detailList = ywSemiFinishedProductEnterDetailService.list(new LambdaQueryWrapper<YwSemiFinishedProductEnterDetail>()
                    .like(StringUtils.isNotBlank(ywSemiFinishedProductEnterMain.getBillNo()), YwSemiFinishedProductEnterDetail::getBillNo, ywSemiFinishedProductEnterMain.getBillNo())
                    .like(StringUtils.isNotBlank(ywSemiFinishedProductEnterMain.getProductCode()), YwSemiFinishedProductEnterDetail::getProductCode, ywSemiFinishedProductEnterMain.getProductCode())
                    .like(StringUtils.isNotBlank(ywSemiFinishedProductEnterMain.getProductName()), YwSemiFinishedProductEnterDetail::getProductName, ywSemiFinishedProductEnterMain.getProductName()));
            if (CollectionUtils.isNotEmpty(detailList)) {
                queryWrapper.in("id", detailList.stream().map(YwSemiFinishedProductEnterDetail::getEnterId).collect(Collectors.toList()));
            } else {
                return Result.OK(new Page<>());
            }
        }
        queryWrapper.ne("enter_status", InventoryConstant.EnterStatusEnum.DELETE.getCode());
        Page<YwSemiFinishedProductEnterMain> page = new Page<YwSemiFinishedProductEnterMain>(pageNo, pageSize);
        IPage<YwSemiFinishedProductEnterMain> pageList = ywSemiFinishedProductEnterMainService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 新增(创建入库单)
     *
     * @param ywSemiFinishedProductEnterMainPage
     * @return
     */
    @AutoLog(value = "半成品入库-添加")
    @ApiOperation(value = "半成品入库-添加", notes = "半成品入库-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody YwSemiFinishedProductEnterMainPage ywSemiFinishedProductEnterMainPage) {
        YwSemiFinishedProductEnterMain ywSemiFinishedProductEnterMain = new YwSemiFinishedProductEnterMain();
        BeanUtils.copyProperties(ywSemiFinishedProductEnterMainPage, ywSemiFinishedProductEnterMain);
        ywSemiFinishedProductEnterMainService.saveMain(ywSemiFinishedProductEnterMain, ywSemiFinishedProductEnterMainPage.getYwSemiFinishedProductEnterDetailList());
        return Result.OK("添加成功！");
    }

    /**
     * 半成品确认入库
     *
     * @param id
     * @return
     */
    @AutoLog(value = "半成品入库-确认入库")
    @ApiOperation(value = "半成品入库-确认入库", notes = "半成品入库-确认入库")
    @PostMapping(value = "/confirmEnter")
    public Result<?> confirmEnter(String id) {
        if (StringUtils.isBlank(id)) return Result.error("请选择确认入库的入库单");
        return ywSemiFinishedProductEnterMainService.confirmEnter(id);
    }

    /**
     * 编辑
     *
     * @param ywSemiFinishedProductEnterMainPage
     * @return
     */
    @AutoLog(value = "半成品入库-编辑")
    @ApiOperation(value = "半成品入库-编辑", notes = "半成品入库-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YwSemiFinishedProductEnterMainPage ywSemiFinishedProductEnterMainPage) {
        YwSemiFinishedProductEnterMain ywSemiFinishedProductEnterMain = new YwSemiFinishedProductEnterMain();
        BeanUtils.copyProperties(ywSemiFinishedProductEnterMainPage, ywSemiFinishedProductEnterMain);
        YwSemiFinishedProductEnterMain ywSemiFinishedProductEnterMainEntity = ywSemiFinishedProductEnterMainService.getById(ywSemiFinishedProductEnterMain.getId());
        if (ywSemiFinishedProductEnterMainEntity == null) {
            return Result.error("未找到对应数据");
        }
        ywSemiFinishedProductEnterMainService.updateMain(ywSemiFinishedProductEnterMain, ywSemiFinishedProductEnterMainPage.getYwSemiFinishedProductEnterDetailList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "半成品入库-通过id删除")
    @ApiOperation(value = "半成品入库-通过id删除", notes = "半成品入库-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        ywSemiFinishedProductEnterMainService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "半成品入库-批量删除")
    @ApiOperation(value = "半成品入库-批量删除", notes = "半成品入库-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.ywSemiFinishedProductEnterMainService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "半成品入库-通过id查询")
    @ApiOperation(value = "半成品入库-通过id查询", notes = "半成品入库-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        YwSemiFinishedProductEnterMain ywSemiFinishedProductEnterMain = ywSemiFinishedProductEnterMainService.getById(id);
        if (null == ywSemiFinishedProductEnterMain) return Result.error("出口仕向数据异常,请联系管理员！");
        if (InventoryConstant.EnterStatusEnum.DELETE.getCode().equals(ywSemiFinishedProductEnterMain.getEnterStatus()))
            return Result.error("出口仕向数据异常,请联系管理员！");
        return Result.OK(ywSemiFinishedProductEnterMain);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "半成品入库-详情通过主表ID查询")
    @ApiOperation(value = "半成品入库-详情主表ID查询", notes = "半成品入库-详情-通主表ID查询")
    @GetMapping(value = "/queryYwSemiFinishedProductEnterDetailByMainId")
    public Result<?> queryYwSemiFinishedProductEnterDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<YwSemiFinishedProductEnterDetail> ywSemiFinishedProductEnterDetailList = ywSemiFinishedProductEnterDetailService.selectByMainId(id);
        return Result.OK(ywSemiFinishedProductEnterDetailList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param ywSemiFinishedProductEnterMain
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YwSemiFinishedProductEnterMain ywSemiFinishedProductEnterMain) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<YwSemiFinishedProductEnterMain> queryWrapper = QueryGenerator.initQueryWrapper(ywSemiFinishedProductEnterMain, request.getParameterMap());
        queryWrapper.ne("enter_status", InventoryConstant.EnterStatusEnum.DELETE.getCode());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<YwSemiFinishedProductEnterMain> queryList = ywSemiFinishedProductEnterMainService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<YwSemiFinishedProductEnterMain> ywSemiFinishedProductEnterMainList = new ArrayList<YwSemiFinishedProductEnterMain>();
        if (oConvertUtils.isEmpty(selections)) {
            ywSemiFinishedProductEnterMainList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            ywSemiFinishedProductEnterMainList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<YwSemiFinishedProductEnterMainPage> pageList = new ArrayList<YwSemiFinishedProductEnterMainPage>();
        for (YwSemiFinishedProductEnterMain main : ywSemiFinishedProductEnterMainList) {
            YwSemiFinishedProductEnterMainPage vo = new YwSemiFinishedProductEnterMainPage();
            BeanUtils.copyProperties(main, vo);
            List<YwSemiFinishedProductEnterDetail> ywSemiFinishedProductEnterDetailList = ywSemiFinishedProductEnterDetailService.selectByMainId(main.getId());
            vo.setYwSemiFinishedProductEnterDetailList(ywSemiFinishedProductEnterDetailList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "半成品入库列表");
        mv.addObject(NormalExcelConstants.CLASS, YwSemiFinishedProductEnterMainPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("半成品入库数据", "导出人:" + sysUser.getRealname(), "半成品入库"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<YwSemiFinishedProductEnterMainPage> list = ExcelImportUtil.importExcel(file.getInputStream(), YwSemiFinishedProductEnterMainPage.class, params);
                for (YwSemiFinishedProductEnterMainPage page : list) {
                    YwSemiFinishedProductEnterMain po = new YwSemiFinishedProductEnterMain();
                    BeanUtils.copyProperties(page, po);
                    ywSemiFinishedProductEnterMainService.saveMain(po, page.getYwSemiFinishedProductEnterDetailList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
